package com.atguigu.guli.service.trade.service.impl;

import com.atguigu.guli.common.util.HttpClientUtils;
import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.trade.entity.Order;
import com.atguigu.guli.service.trade.service.OrderService;
import com.atguigu.guli.service.trade.service.WeixinPayService;
import com.atguigu.guli.service.trade.util.WeixinPayProperties;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WeixinPayServiceImpl implements WeixinPayService {
    @Autowired
    private WeixinPayProperties weixinPayProperties;
    @Autowired
    private OrderService orderService;

    @Override
    public Map<String, Object> createNative(String orderNo, String remoteAddr) {
        //根据课程订单号获取订单
        Order order = orderService.getOrderByOrderNo(orderNo);

        //发送httpclient远程调用请求
//        HttpClientUtils client = new HttpClientUtils("https://api.mch.weixin.qq.com/pay/unifiedorder");
        HttpClientUtils client = new HttpClientUtils("https://api.mch.weixin.qq.com/sandboxnew/pay/unifiedorder");
        //组装参数
        HashMap<String, String> params = new HashMap<>();
        params.put("appid",weixinPayProperties.getAppId()); //关联的公众号的appid
        params.put("mch_id",weixinPayProperties.getPartner()); //商户号
        params.put("nonce_str", WXPayUtil.generateNonceStr()); //生成随机字符串,防止请求重放攻击
//        params.put("sign",WXPayUtil.generateSignature());
        params.put("body",order.getCourseTitle());
        params.put("out_trade_no",orderNo); //统一下单成功并支付后，订单号不能重复
        params.put("total_fee",order.getTotalFee() + "");
        params.put("spbill_create_ip",remoteAddr);
        params.put("notify_url",weixinPayProperties.getNotifyUrl()); //回调url
        params.put("trade_type","NATIVE");
        params.put("product_id",order.getCourseId());
//        params.put("sign",WXPayUtil.generateSignature(params,weixinPayProperties.getPartnerKey()));

        //将参数转换成xml字符串格式：生成带有签名的xml格式字符串
        String xmlParams = null;
        try {
            //将参数转换成xml字符串格式：生成带有签名的xml格式字符串
            xmlParams = WXPayUtil.generateSignedXml(params, weixinPayProperties.getPartnerKey());
            System.out.println(xmlParams);

            client.setXmlParam(xmlParams);//将参数放入请求对象的方法体
            client.setHttps(true);//使用https形式发送
            client.post();//发送请求
            String resultXml = client.getContent();//得到响应结果
            //将xml响应结果转成map对象
            Map<String, String> resultMap = WXPayUtil.xmlToMap(resultXml);

            //错误处理
            if("FAIL".equals(resultMap.get("return_code")) || "FAIL".equals(resultMap.get("result_code"))){
                log.error("微信支付统一下单错误 - "
                        + "return_code: " + resultMap.get("return_code")
                        + "return_msg: " + resultMap.get("return_msg")
                        + "result_code: " + resultMap.get("result_code")
                        + "err_code: " + resultMap.get("err_code")
                        + "err_code_des: " + resultMap.get("err_code_des"));

                throw new GuliException(ResultCodeEnum.PAY_UNIFIEDORDER_ERROR);
            }

            //组装需要的内容
            Map<String, Object> map = new HashMap<>();
            map.put("result_code", resultMap.get("result_code"));//响应码
            map.put("code_url", resultMap.get("code_url"));//生成二维码的url
            map.put("course_id", order.getCourseId());//课程id
            map.put("total_fee", order.getTotalFee());//订单总金额
            map.put("out_trade_no", orderNo);//订单号

            return map;
        } catch (Exception e) {
            throw new GuliException(ResultCodeEnum.PAY_UNIFIEDORDER_ERROR);
        }
    }
}
